﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using CS.model;

namespace CS.DAL
{
    public class OrderService
    {
        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="list">购买的商品集合</param>
        /// <param name="totalMoney">商品总金额</param>
        /// <param name="adminId">员工编号</param>
        /// <returns>如果添加成功返回true，否则返回false</returns>
        public bool InsertOrder(List<BuyGoods> list, double totalMoney, int adminId)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=UserInfo;Integrated Security=True");
            try
            {
                //TODO:后续使用事务完善程序流程
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                //1.插入订单
                string sql = string.Format("insert into OrderInfo (OrderMoney,Usersid) values ({0},{1})", totalMoney, adminId);
                cmd.CommandText = sql;
                int count = cmd.ExecuteNonQuery();//执行插入语句获取受影响的行数
                if (count == 0)
                {//判断是否插入数据成功
                    return false;
                }
                //2.查询生成的订单编号
                sql = "select @@identity";
                cmd.CommandText = sql; //查询最近一次插入语句生成的标识列的值
                object orderId = cmd.ExecuteScalar();
                if (orderId == null)
                {//没有查询到 则表示生成订单是失败的
                    return false;
                }
                //3.利用生成的订单编号添加商品数据
                foreach (BuyGoods item in list)
                {
                    sql = string.Format(
                        "insert into OrderGoods values ({0},'{1}',{2},{3},{4},{5})",
                        orderId, item.GoodsCode, item.SalePrice, item.BuyCount, item.XiaoJi, item.Coupon);
                    cmd.CommandText = sql;
                    //默认认为都会执行成功，暂时不要考虑添加影响行数
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }

            return true;
        }
    }
}
